public class OpportunitySolutionExtensionController{
    public List<SolutionComponent__c> components{get;set;}
    public List<string> componentFields{get;set;}
    public Solution__c soln {get; set;}
    public String compIdx{get;set;}    
    static integer flag;
    public Boolean IsTechnology{get;set;}
    public Boolean IsConsulting{get;set;}
    public Boolean IsOutsourcing{get;set;}
    
    private List<string> solFieldsToActivate;
 
    public Boolean IsAccountSolution{get; set;}
    
    public Boolean disableInput{get; set;}
    public Boolean isError{get;set;}
    public string toDelete{ get; set; }
    
    public String SolutionComponentsTitle{get; set;}
    
    public String RecType{get;set;}
    private ApexPages.StandardController solnController;
              
    public OpportunitySolutionExtensionController(ApexPages.StandardController stdController) {
        if (!Test.isRunningTest())
        {
        setAllSolFieldsActive();
        solFieldsToActivate.add('Opportunity__r.currencyIsoCode');
        stdController.addFields(solFieldsToActivate);        
        }
        
        
        solnController = stdController;
        soln = (Solution__c)stdController.getRecord();       
            
    }
        
	private void setAllSolFieldsActive(){
        solFieldsToActivate = new List<string>();         
        Schema.DescribeSObjectResult solobj = Solution__c.SObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> allFieldsMap = solobj.fields.getMap();

        for(String fldName : allFieldsMap.keySet()){
            Schema.SObjectField fld = allFieldsMap.get(fldName);
            DescribeFieldResult fieldResult = fld.getDescribe();
            if(fieldResult.isCustom()){
                
                    string fieldName = fieldResult.getName();
                    solFieldsToActivate.add(fieldName);
            }
        }        
    }
    
	private void SetComponentTitle(){                         
        if(IsTechnology){
			SolutionComponentsTitle = 'Modules';                  
        }
        else if (IsConsulting){
                
           SolutionComponentsTitle = 'Services';
        }
        else if (IsOutsourcing){              
            SolutionComponentsTitle = 'Countries';
        }
        else{
        	SolutionComponentsTitle = RecType;
        }
               
        
    } 
    public void Initialise(){        
        isError = false;
        currencyDefault();
        components = new List<SolutionComponent__c>();
        Schema.DescribeSObjectResult R = Solution__c.SObjectType.getDescribe();
        
        Schema.DescribeSObjectResult solcomp = SolutionComponent__c.SObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> allFieldsMap = solcomp.fields.getMap();
        String SOQLSelect = '';
        for(String fldName : allFieldsMap.keySet()){
            Schema.SObjectField fld = allFieldsMap.get(fldName);
            DescribeFieldResult fieldResult = fld.getDescribe();
            string fieldName = fieldResult.getName();
            System.debug('Got field:'+fieldName);
            if(SOQLSelect != ''){
                SOQLSelect += ',' + fieldName;
            }
            else{
                SOQLSelect += 'select ' + fieldName;
            }     
        }             
        if(soln.id !=null){
            String SOQLStmt =SOQLSelect + ' from SolutionComponent__c where Solution__r.id =' + '\'' + soln.id + '\'';        
            components = Database.query(SOQLStmt);
        }              
        Map<ID,Schema.RecordTypeInfo> recTypesMap = R.getRecordTypeInfosByID();
        Schema.RecordTypeInfo recTypeInst = recTypesMap.get(soln.RecordTypeId);         
        RecType = recTypeInst.getName();       
        IsTechnology = (RecType == 'HR Technology');
        IsConsulting = (RecType == 'HR Consulting');
        IsOutsourcing = (RecType == 'HR Outsourcing');
        
        if(soln.Account__c != null)
        {
                IsAccountSolution = true;
        }
        else
        {
                IsAccountSolution = false;
        }
        SetComponentTitle();       
        techodisable();       
    }
    
    Public void currencyDefault()
    {
        
        if(soln.id != null){
        
        system.debug('solution id ' + soln.Opportunity__r.currencyIsoCode);
        Solution__c sln = [select CurrencyIsoCode,Opportunity__r.id from Solution__c where id =: soln.id]; 
        opportunity opty = [select CurrencyIsoCode from opportunity where id =: soln.Opportunity__r.id];
        
        //currIso =  soln.Opportunity__r.currencyIsoCode;
       
        soln.currencyIsoCode = soln.Opportunity__r.currencyIsoCode;
        system.debug('ISO Code Is' + soln.currencyIsoCode);
                          
        system.debug('solution id ++++  ' + soln.id);
       
        }    
    }
    
    public void beforenew()
    {
     soln = (Solution__c)solnController.getRecord();
     if(soln.Product__c==null)
     {
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please select the Technology/Service Level for solution'));
     }
     else if( !ValidateComponentsHaveValueSet())
     {
     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please ensure that all Solution Components have a selected value for the component field dropdown'));
     }
     else
     {
      NewSolutionComponent();
     }
    }
    public void NewSolutionComponent(){ 
        
      
        SolutionComponent__c solComp = new SolutionComponent__c();
        solComp.ParentType__c = soln.product__c;
        solComp.Solution__c = null;
        components.add(solComp);
        techodisable();
       
    }
      
    
 public PageReference save() {
 	 if(!ValidateComponentsHaveValueSet())
      {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please ensure that all Solution Components have a selected value for the component field dropdown'));
      }
      
         else
      {        
        Savepoint sp = Database.setSavepoint();        
      
        PageReference retPage = null;
        try {           
            if(IsAccountSolution)
            {
                if(soln.Opportunity__c == null){
                    DummyOptyHolder__c optyCustomSetting = DummyOptyHolder__c.getInstance();
                    string DumyOptyId = optyCustomSetting.OptyId__c;
                    soln.Opportunity__c=DumyOptyId;
                }
                soln.IsAccountSolution__c = true;               
                system.debug('Account Saving Solution');
                solnController.save();
                soln = (Solution__c)solnController.getRecord();
                               
                retPage = new PageReference('/'+soln.Account__c);
                system.debug('Set Account Save Page Solution'); 
                
            }
            else
            {
                system.debug('Not Account Saving Solution');
                solnController.save();              
                soln = (Solution__c)solnController.getRecord();                
                retPage=new PageReference('/'+soln.Opportunity__c);
                system.debug('Set Opty Save Page Solution');                
            }
            
            
            
            for (SolutionComponent__c solComp : components){
                if(solComp.Solution__c == null)
                {
                    solComp.Solution__c = solnController.getId();                   
                }
              
                solComp.CurrencyIsoCode = soln.CurrencyIsoCode;
                system.debug('solution component currencycode' + solComp.CurrencyIsoCode);
                    
            }

            if(components.size() > 0)
            {                           
                Database.upsert(components);
            }
            if(ApexPages.getMessages().size()>0)
            {
                return null;
            }
            return retPage;                              
                                         
        }
        catch (Exception e) {           
            Database.rollback(sp);
            System.debug('******** exception ' + e);
            isError = true;
            ApexPages.addMessages(e);
        }   
        }
        return null;
        
    }
    
    public PageReference cancel(){
      
        PageReference p;
        p =  solnController.cancel();
        try{
            soln = (Solution__c)solnController.getRecord(); 
            
            if(IsAccountSolution)
            {
                p=new PageReference('/'+soln.Account__c);
            }
            else
            {
                 p=new PageReference('/'+soln.Opportunity__c);  
            }
        }
        catch(Exception e){
            System.debug('******* exception' + e);        
        }
        return p;
    }
   	public void copySectionItem(){  		
   	
     if(!ValidateComponentsHaveValueSet())
      {
      ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please ensure that all Solution Components have a selected value for the component field dropdown'));
      }
      else
      {        	    
        try
        {
	        List<SolutionComponent__c> modcomponents = new List<SolutionComponent__c>();
	        System.debug('Component Index Reference' + compIdx);
	        String[] columnparts = compIdx.split(':');
	        
	        Integer idx =0;
	        Integer tableRow;
	        
	        for(String tkn : columnparts){ 
	                
				if(tkn == 'CopyColumn'){
					tableRow = Integer.valueOf(columnparts[idx-1]);
					System.debug('Table Row Is: ' +tableRow );
				}
				idx++;
	        }
	                
			idx =0;
			for(SolutionComponent__c comp: components){
				modcomponents.add(comp);
				if(idx == tableRow){
					SolutionComponent__c newsolComp = comp.Clone(false);
					modcomponents.add(newsolComp);
				}
				idx++;          
	        }
	        components = modcomponents;
        }
		catch(Exception e){
			System.Debug('Error while copying components:'+e);
			ApexPages.addMessages(e);
		}
      }
   }
   
   public void deleteSectionItem() {
        SolutionComponent__c solComp;
        System.debug('Component Index Reference' + compIdx);
        String[] columnparts = compIdx.split(':');
        
        Integer idx =0;
        Integer tableRow;
        
        for(String tkn : columnparts){ 
                
                if(tkn == 'DeleteColumn'){
                        tableRow = Integer.valueOf(columnparts[idx-1]);
                        System.debug('Table Row Is: ' +tableRow );
                }
                idx++;          
        }
        
        System.Debug('todelete'+todelete);
        if(this.toDelete != '' || this.toDelete != null){
            try{                            
                                                        List<SolutionComponent__c> modcomponents = new List<SolutionComponent__c>();
                idx =0;
                for(SolutionComponent__c comp: components){
                                        if(idx != tableRow){
                                                 modcomponents.add(comp);
                                        }
                                        idx++;
                }
                components = modcomponents;
                solComp = [select id from SolutionComponent__c where id = : this.toDelete];                   
                delete solComp;
                
                              
            }
            catch(Exception e){
                System.Debug('Error while deletion:'+e);
            }
            techodisable();
                        

        }        
    }
    
      
    Private boolean ValidateComponentsHaveValueSet()
    {
     boolean Flag1;
     if(components.size()==0)
     {
      Flag1=true;
     }
     else{
     for(integer i=0;i<components.size();i++)
            {                           
               if(components.get(i).component__c==null)
               {
                Flag1=false;
               }
               else
               {
                Flag1=true;
               }
            }
            }
       return Flag1;     
    }
    
    
    public void techodisable(){
        if(components.size() > 0){
            disableInput = true;
        }
        else{
            disableInput = false;
        }
    }
}